#!/bin/bash
# Component Validation Script
# Usage: bash scripts/validate-component.sh ComponentName

set -e

COMPONENT_NAME=$1

if [ -z "$COMPONENT_NAME" ]; then
  echo "❌ 错误: 缺少组件名称"
  echo "用法: bash scripts/validate-component.sh ComponentName"
  exit 1
fi

echo "🔍 验证组件: ${COMPONENT_NAME}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

ERROR_COUNT=0

# 验证 fields/aiComponents.ts
echo "检查: fields/aiComponents.ts"
if npx eslint src/components/editor/schema/fields/aiComponents.ts --quiet; then
  echo "  ✓ fields/aiComponents.ts 通过"
else
  echo "  ✗ fields/aiComponents.ts 存在错误"
  ERROR_COUNT=$((ERROR_COUNT + 1))
fi

# 验证 edit/aiComponents.ts
echo "检查: edit/aiComponents.ts"
if npx eslint src/components/editor/schema/edit/aiComponents.ts --quiet; then
  echo "  ✓ edit/aiComponents.ts 通过"
else
  echo "  ✗ edit/aiComponents.ts 存在错误"
  ERROR_COUNT=$((ERROR_COUNT + 1))
fi

# 验证 preview 组件
PREVIEW_PATH="src/components/editor/schema/preview/components/${COMPONENT_NAME}"
if [ -d "$PREVIEW_PATH" ]; then
  echo "检查: ${PREVIEW_PATH}/**/*.{ts,tsx}"
  if npx eslint "${PREVIEW_PATH}/**/*.{ts,tsx}" --quiet; then
    echo "  ✓ Preview 组件通过"
  else
    echo "  ✗ Preview 组件存在错误"
    ERROR_COUNT=$((ERROR_COUNT + 1))
  fi
else
  echo "  ⚠️  Preview 组件目录不存在: ${PREVIEW_PATH}"
fi

# 检查 Right 面板渲染
RIGHT_RENDER_FILES=$(find src/components/editor/Right -name "render${COMPONENT_NAME}.tsx" -o -name "render${COMPONENT_NAME}.ts" 2>/dev/null)
if [ -n "$RIGHT_RENDER_FILES" ]; then
  echo "检查: Right 面板渲染逻辑"
  if npx eslint $RIGHT_RENDER_FILES --quiet; then
    echo "  ✓ Right 渲染函数通过"
  else
    echo "  ✗ Right 渲染函数存在错误"
    ERROR_COUNT=$((ERROR_COUNT + 1))
  fi
else
  echo "  ⚠️  未发现自定义面板 render 文件（跳过）"
fi

# AI 注册核对
echo "检查: AI 专区注册"
if grep -q "${COMPONENT_NAME}" src/components/editor/schema/preview/aiCustomComponents.ts; then
  echo "  ✓ preview/aiCustomComponents.ts 已注册"
else
  echo "  ✗ preview/aiCustomComponents.ts 缺少 ${COMPONENT_NAME}"
  ERROR_COUNT=$((ERROR_COUNT + 1))
fi

if grep -q "aiCustomComponents" src/components/editor/schema/preview/index.ts; then
  echo "  ✓ preview/index.ts 已聚合导出 AI 组件"
else
  echo "  ✗ preview/index.ts 缺少 aiCustomComponents 聚合"
  ERROR_COUNT=$((ERROR_COUNT + 1))
fi

if ! grep -q "${COMPONENT_NAME}" src/constants/constants.ts; then
  echo "  ✗ constants.ts 中缺少 ${COMPONENT_NAME} 注册"
  ERROR_COUNT=$((ERROR_COUNT + 1))
else
  echo "  ✓ constants.ts 已注册组件"
fi

# 覆盖率提示
if node scripts/component-coverage-report.js "${COMPONENT_NAME}"; then
  echo "  ✓ 生成覆盖率报告"
else
  echo "  ⚠️  覆盖率报告执行完成（请根据提示修复）"
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ $ERROR_COUNT -eq 0 ]; then
  echo "✓ 组件验证通过"
  exit 0
else
  echo "✗ 组件验证失败 (${ERROR_COUNT} 个错误)"
  echo ""
  echo "修复建议:"
  echo "1. 检查 ESLint 输出的具体错误"
  echo "2. 运行 npx eslint <file> 查看详细错误"
  echo "3. 修复后重新运行此脚本"
  exit 1
fi
